package org.example.myleet.p1006;

import java.util.Deque;
import java.util.LinkedList;

public class Solution {

    private static final int MULTIPLY = 0;
    private static final int DIVIDE = 1;
    private static final int PLUS = 2;
    private static final int SUBTRACT = 3;

    /**
     * 11 ms
     * 利用stack对算式进行尽力计算，将可以计算的部分先计算完，未能计算的则存压入栈中
     */
    public int clumsy(int N) {
        Deque<Long> stack = new LinkedList<>();
        //初始化
        stack.push((long) N);
        int count = 0;
        for (int i = N-1; i >= 1; --i) {
            //获取本回合的计算符号
            int mark = count % 4;
            //对于乘、除、加，都是可以直接先计算的，减法则相当于负数，减法如果后面没有值，就是加一个负数，如果后面有乘法则不能先计算，入栈
            switch (mark) {
                case MULTIPLY: {
                    stack.push(stack.pop() * i);
                    break;
                }
                case DIVIDE: {
                    stack.push(stack.pop() / i);
                    break;
                }
                case PLUS: {
                    stack.push(stack.pop() + i);
                    break;
                }
                case SUBTRACT: {
                    stack.push((long) (-i));
                    break;
                }
            }
            ++count;
        }
        long result = 0;
        while (!stack.isEmpty()) {
            result += stack.pop();
        }
        return (int) result;
    }
}
